package com.example.myapplication.utils;

import android.os.Environment;

import java.io.File;

public class StorageUtils {
    private StorageUtils() {
    }

    private static StorageUtils storageUtils;

    public static StorageUtils getInstance() {
        if (storageUtils == null) {
            synchronized (StorageUtils.class) {
                if (storageUtils == null) {
                    storageUtils = new StorageUtils();
                }
            }
        }
        return storageUtils;
    }

    /**
     * 判断安卓设备是否存在内存卡
     */
    public boolean isExistSDCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * create public dictionary for this app
     */
    /*
    public File createAppPublicDir() {
        if (isExistSDCard()) {
            File sdDir = Environment.getExternalStorageDirectory();
            File appDir = new File(sdDir, FileInterface.APP_DIR);
            if (!appDir.exists()) {
                boolean mkdir = appDir.mkdir();
                if (!mkdir) return null;
            }
            Contains.PATH_APP_DIR = appDir.getAbsolutePath();//将获取到的路径存进公共类中
            return appDir;
        }
        return null;
    }
    */
    public File createAppPublicDir() {
        File appPublicDir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            appPublicDir = new File(Environment.getExternalStorageDirectory(), FileInterface.APP_DIR);
        } else {
            appPublicDir = new File(Environment.getDataDirectory(), FileInterface.APP_DIR);
        }
        if (!appPublicDir.exists()) {
            appPublicDir.mkdirs();
        }
        return appPublicDir;
    }

    /**
     * To create a subdirectory for the project
     */
    public File createAppSubdirectory(String dir) {
        File publicDir = createAppPublicDir();
        if (publicDir == null) System.out.println("publicDir创建失败");
        if (publicDir != null) {
            File subDir = new File(publicDir, dir);
            if (!subDir.exists()) {
                boolean mkdirs = subDir.mkdirs();
            }
            return subDir;
        }
        return null;
    }

    public static boolean deleteFileInAppDir(String fileName) {
        File dir = new File(Contains.PATH_SUB_RECORD);
//        System.out.println("找到了文件夹。");
        File targetFile = new File(dir, fileName);
        if (targetFile.exists()) {
            return targetFile.delete();
        }
        return false;
    }

}
